let enumeration = require('../../../constant/enumeration');
let code = require('../../../constant/code');
let pomelo = require('pomelo');
let dao = require('../../../dao/commonDao');
let rechargeLogger = require('pomelo-logger').getLogger('recharge');
let rechargeServices = require('../../../services/rechargeServices');
let userInfoServices = require('../../../services/userInfoServices');
let logger = require('pomelo-logger').getLogger('recharge');
let util = require('../../../util/utils');
let moment = require('moment');

let alipaySdk = require('../../../services/aliPayServvice');


module.exports = function (app, http) {



    http.post('/payAliOrder', async function (req, res) {

        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');

        try {
            let bodys = req.body;
            // logger.info(`get pay bodys = ${JSON.stringify(bodys)}`);
            const success = alipaySdk.checkNotifySign(bodys);
            let { trade_status, out_trade_no, trade_no } = bodys;
            logger.info(`[${out_trade_no}] trade_status =  ${trade_status} trade_no = ${trade_no}  `);

            if (success) {

                if (trade_status == "TRADE_SUCCESS") {
                    //如果充值成功 给玩家更新钻石信息
                    let orderData = await dao.findOneAndUpdate('orderModel', { 'status': 0, 'orderNo': out_trade_no }, { status: 1, endTime: moment().format('x') });
                    if (orderData) {
                        let count = (orderData.gold || 0) + (orderData.addGold || 0);
                        let userData = await dao.findOneAndUpdate('userModel', { uid: orderData.uid }, { tradeNo: trade_no, $inc: { gold: count } });
                        if (userData) {
                            await userInfoServices.updateUserDataNotify(orderData.uid, userData.frontendId, { gold: userData.gold });
                            // 创建赠送记录
                            let saveData = { uid: -1, gainUid: orderData.uid, type: 'gold', count: count, createTime: Date.now() };
                            dao.createData("adminGrantRecordModel", saveData);
                        }
                    } else {
                        logger.error(`order data  status error   `);
                    }
                } else {
                    //交易失败更新数据   
                    dao.findOneAndUpdate('orderModel', { orderNo: out_trade_no }, { status: -1, endTime: moment().format('x') });
                }
                res.send('success');
            } else {
                logger.error(`sign error mySign = ${mySign} sign = ${sign} `);
            }
            res.end('');
        } catch (e) {
            logger.error(`payOrder err = ${JSON.stringify(e)} `);
            res.end('');
        }
    });


    http.get('/payOrder', async function (req, res) {

        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        res.header('Access-Control-Allow-Headers', 'Content-Type');

        try {

            let data = req.query;
            logger.info(`get pay response = ${JSON.stringify(data)}`);
            let { pid, trade_no, out_trade_no, type, name, money, trade_status, sign, sign_type } = data;
            let singData = { pid, trade_no, out_trade_no, type, name, money, trade_status };
            //let key = '1wIbf9J0VmiUSsKoKxH34o1TiAZebxqC';
            let key = 'qTmwtKYXNXOpxx9aWIb26sEZx4WBDYUx';
            let mySign = util.sign(singData, key);
            if (mySign == sign) {

                if (trade_status == "TRADE_SUCCESS") {
                    //如果充值成功 给玩家更新钻石信息
                    let orderData = await dao.findOneAndUpdate('orderModel', { 'status': 0, 'orderNo': out_trade_no }, { status: 1, endTime: moment().format('x') });
                    if (orderData) {
                        let count = (orderData.gold || 0) + (orderData.addGold || 0);
                        let userData = await dao.findOneAndUpdate('userModel', { uid: orderData.uid }, { $inc: { gold: count } });
                        if (userData) {
                            await userInfoServices.updateUserDataNotify(orderData.uid, userData.frontendId, { gold: userData.gold });
                            // 创建赠送记录
                            let saveData = {
                                uid: -1,
                                gainUid: orderData.uid,
                                type: 'gold',
                                count: count,
                                createTime: Date.now()
                            };
                            dao.createData("adminGrantRecordModel", saveData);
                        }
                    } else {
                        logger.error(`order data  status error   `);
                    }
                } else {
                    //交易失败更新数据   
                    dao.findOneAndUpdate('orderModel', { orderNo: out_trade_no }, { status: -1, endTime: moment().format('x') });
                }
            } else {
                logger.error(`sign error mySign = ${mySign} sign = ${sign} `);
            }
            res.end('succcess');
        } catch (e) {
            logger.error(`payOrder err = ${JSON.stringify(e)} `);
            res.end('succcess');
        }

    });

};